package cn.i96688.scanclient.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.math.BigDecimal;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import com.alibaba.fastjson.JSONObject;
import cn.i96688.scanclient.bean.PayLog;
import cn.i96688.scanclient.bean.Status;
import cn.i96688.scanclient.service.ScanPayService;
import cn.i96688.scanclient.service.impl.ScanPayServiceImpl;
import cn.i96688.scanclient.ui.PaymentProgress.OrderQueryListener;
import cn.i96688.scanclient.utils.Constants;
import cn.i96688.scanclient.utils.LocalStore;
import cn.i96688.scanclient.utils.PayUtil;

/**
 * 条码支付界面
 * @author xys
 *
 */
@SuppressWarnings("serial")
public class ScanPayForm extends SuperForm{
//	private Logger log=Logger.getLogger(ScanPayForm.class);
	private ScanPayService scanPayService=new ScanPayServiceImpl();
	private PaySucListener payListener=null;
	private float rate=0.35F;
	
	private BorderLayout mainLayout=new BorderLayout();
	private AmountPane amountPane;
	private KeybordPane keybordPane;
	private JButton payBtn;
	private String barcode="";
	private String curOrderNo="";
	
	private int width=0;//宽
	private int height=0;//高
	private int amountSize=16;//金额字体大小
	private int keyboardSize=22;//键盘字体大小
	
	private final String del="X";
	
	private PaymentProgress payDialog=null;
	public ScanPayForm(){
		this.setTitle("扫码支付");
		setIconImage(MainForm.icon);
		this.setVisible(false);
		setAlwaysOnTop(true);//显示到最前面
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); 
		//监听关闭按钮的点击操作 
		this.addWindowListener(new WindowAdapter(){ 
			public void windowClosing(WindowEvent e) { 
				hideForm();
			}
		});
		JSONObject jsonConfig=LocalStore.getInstance().getPayDialogConfig();
		if(jsonConfig.size()>=4){
			width=jsonConfig.getIntValue("width");
			height=jsonConfig.getIntValue("height");
			amountSize=jsonConfig.getIntValue("amountSize");
			keyboardSize=jsonConfig.getIntValue("keyboardSize");
		}else{
			Dimension screenSize =Toolkit.getDefaultToolkit().getScreenSize();
			width=(int)(screenSize.width*rate);
			height=width+40;
			JSONObject config=new JSONObject();
			config.put("width", width);
			config.put("height", height);
			config.put("amountSize", amountSize);
			config.put("keyboardSize", keyboardSize);
			LocalStore.getInstance().writePayDialogConfig(config);
		}

		this.setLayout(mainLayout);
		amountPane=new AmountPane();
		add(amountPane, BorderLayout.NORTH);
		keybordPane=new KeybordPane();
		add(keybordPane, BorderLayout.CENTER);
		add(new JLabel(" "), BorderLayout.WEST);
		add(new JLabel(" "), BorderLayout.EAST);
		
		
		//底部按钮
		SuperPane southPane=new SuperPane();
		add(southPane, BorderLayout.SOUTH);
		southPane.setLayout(new GridBagLayout());
		payBtn=new JButton("支  付");
		payBtn.setFont(new Font("宋体",Font.BOLD,20));
		payBtn.addActionListener(this);
		southPane.add(new JLabel(" "),new GBC(0,0));
		southPane.add(payBtn,new GBC(1,0,1,3).setFill(GBC.BOTH).setWeight(1,0).setInsets(4,0,2,0));
		southPane.add(new JLabel(" "),new GBC(2,0));
		southPane.add(new JLabel(" "),new GBC(0,1));
		southPane.add(new JLabel(" "),new GBC(0,2));
		
		setSize(width,height);
		
		Dimension size=payBtn.getPreferredSize();
		if(size.height<70){
		    size.height=70;
		    payBtn.setPreferredSize(size);
		}
		payDialog=new PaymentProgress(this);
		payDialog.setOrderQueryListener(orderQuery);
	}
	public int getAmountSize(){
		return amountSize;
	}
	public int getKeyboardSize(){
		return keyboardSize;
	}
	public void updateConfig(JSONObject config){
		width=config.getIntValue("width");
		if(config.getIntValue("width")>0) {
			width=config.getIntValue("width");
		}
		if(config.getIntValue("height")>0) {
			height=config.getIntValue("height");
		}
		if(config.getIntValue("amountSize")>0) {
			amountSize=config.getIntValue("amountSize");
		}
		if(config.getIntValue("keyboardSize")>0) {
			keyboardSize=config.getIntValue("keyboardSize");
		}
		setSize(width,height);
		amountPane.updateFont();
		keybordPane.updateFont();
	}
	
	/**
	 * 待支付订单处理
	 */
	private void orderPending(){
		if("".equals(curOrderNo))
			return;
		JSONObject json=scanPayService.queryOrder(curOrderNo);
		int status=json.getIntValue(Status.NAME);
		if(status==Status.INT_FAIL){//失败
			JOptionPane.showMessageDialog(this, json.getString(Status.NAME_MSG), "支付失败", JOptionPane.ERROR_MESSAGE);
		}else if(status==3){//待支付中
			JOptionPane.showMessageDialog(this, "该笔订单还在支付中，请跟消费者确认后再作处理", "订单待支付", JOptionPane.WARNING_MESSAGE);
		}
		hideForm();
	}
	/**
	 * 支付事件
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		curOrderNo="";
		if(barcode==null || barcode.length()==0){
			JOptionPane.showMessageDialog(this, "条码失效，请重新扫码支付", "支付校验失败", JOptionPane.ERROR_MESSAGE);
			return;
		}
		BigDecimal payableAmount=amountPane.getPayableAmount();
		if(payableAmount.compareTo(BigDecimal.ZERO)<1){
			JOptionPane.showMessageDialog(this, "应付金额不能小于等于0", "支付校验失败", JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		PayLog.getInstance().addLog("当前条码["+barcode+"]，应该金额["+payableAmount+"],启动支付进度框");
		EventQueue.invokeLater(new Runnable(){
			@Override
			public void run() {
				pay();
		}});
		payDialog.showForm();
		
	}
	private void pay(){
		BigDecimal payableAmount=amountPane.getPayableAmount();
		JSONObject msg=scanPayService.pay(payableAmount.toString(), barcode);
		int status=msg.getIntValue(Status.NAME);
		if(status==Status.INT_FAIL){
			payDialog.hideForm();
			JOptionPane.showMessageDialog(this, msg.getString(Status.NAME_MSG), "支付失败", JOptionPane.ERROR_MESSAGE);
		}else{
			msg.put("payableAmount", payableAmount);
			firePaySuc(msg);
			
			String orderStatus=msg.getString("orderStatus");
			//订单还在支付中
			if(Constants.ORDER_PENDING.equals(orderStatus)){
				curOrderNo=msg.getString("orderNo");
			}else{
				hideForm();
			}
			
		}
	}
	private void hideForm(){
		barcode="";
		amountPane.payableAmount.setText("");
		payDialog.hideForm();
		this.setVisible(false);
	}
	
	public void setBarcode(String barcode){
		PayLog.getInstance().addLog("扫入条码["+barcode+"]，弹出支付框");
		amountPane.payableAmount.setText("");
		this.barcode=barcode;
	}
	
	
	private void calculate(String name){
		if(name.equals(del)){
			String txt=amountPane.payableAmount.getText();
			txt=txt==null?"":txt;
			if(txt.length()>0){
				txt=txt.substring(0,txt.length()-1);
			}
			amountPane.payableAmount.setText(txt);
		}else{
			String txt=amountPane.payableAmount.getText();
			if(txt==null)
				txt="";
			String ptxt=txt+name;
			if("0".equals(txt) || PayUtil.isNumber(ptxt)){
				String repTxt="";
				if(ptxt.equals("0.")){
					repTxt=ptxt;
				}else if(ptxt.lastIndexOf(".")==ptxt.indexOf(".")){
					repTxt=ptxt;
				}else{
					repTxt=new BigDecimal(ptxt).toString();
				}
				amountPane.payableAmount.setText(repTxt);
			}
		}
	}
	
	public void setPaySucListener(PaySucListener l){
		payListener=l;
	}
	private void firePaySuc(JSONObject data){
		if(payListener==null)
			return;
		payListener.insertFirst(data);
	}
	
	/**
	 * 金额数量显示
	 * @author xys
	 *
	 */
	class AmountPane extends SuperPane{
		private JLabel payableLab=new JLabel();
		private JTextField payableAmount=new JTextField();
		
		void setBorder(JLabel label){
			label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
			label.setBackground(Color.WHITE);
			
		}
		AmountPane(){
//			super.setBackground(Color.BLUE);
			
	        setLayout(new GridBagLayout()); //创建网格组布局方式对象 
	        
	        //应付金额
	        payableLab.setText("付款金额");
	       
	        payableAmount.setEditable(false);
	        Dimension size=payableAmount.getPreferredSize();
	        size.height=35;
	        payableAmount.setPreferredSize(size);
	        
	        add(payableLab,new GBC(0,0).setInsets(2,4,2,2));
	        add(payableAmount,new GBC(1,0).setFill(GBC.HORIZONTAL).setWeight(1, 0).setInsets(2,2,2,4));
	        
	        updateFont();
		}
		
		
		void updateFont(){
			payableLab.setFont(new Font("宋体",Font.PLAIN,amountSize));
			payableAmount.setFont(new Font("宋体",Font.PLAIN,amountSize));
			
			
		}
		
		BigDecimal getPayableAmount(){
			try{
				String txt=payableAmount.getText();
				if(txt==null || txt.length()==0)
					return BigDecimal.ZERO;
				return new BigDecimal(payableAmount.getText());
			}catch(Exception e){
				PayLog.getInstance().addLog("获取应付金额失败："+payableAmount.getText());
				PayLog.getInstance().addLogs(e);
				return BigDecimal.ZERO;
			}
		}
	}
	/**
	 * 小键盘显示
	 * @author xys
	 *
	 */
	class KeybordPane extends SuperPane{
		private GridLayout layout=null;
		KeybordPane(){
			layout=new GridLayout(0,4,2,2);//创建网格组布局方式对象 
	        setLayout(layout); 
	        addItem("1");
	        addItem("2");
	        addItem("3");
	        KeybordItem item=addItem(del);
	        Image image=Toolkit.getDefaultToolkit().getImage(MainForm.class.getResource("/del.png"));
	        Image img2= image.getScaledInstance(35, 35, Image.SCALE_DEFAULT);
	        javax.swing.ImageIcon ii=new javax.swing.ImageIcon(img2);
	        
	        item.setIcon(ii);
	        item.setText("");
	        
	        addItem("4");
	        addItem("5");
	        addItem("6");
	        addItem(".");
	        
	        addItem("7");
	        addItem("8");
	        addItem("9");
	        addItem("0");
	        
	        updateFont();
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			KeybordItem btn=(KeybordItem)e.getSource();
			calculate(btn.getName());
		}
		KeybordItem addItem(String txt){
			KeybordItem item=new KeybordItem(txt);
			item.addActionListener(this);
			add(item);
			return item;
		}
		void updateFont(){
			Component comp[]=getComponents();
			for(int i=0;i<comp.length;i++){
				if(comp[i] instanceof KeybordItem){
					comp[i].setFont(new Font("宋体",Font.BOLD,keyboardSize));
				}
			}
		}
	}
	
	class KeybordItem extends JButton{
		KeybordItem(String txt){
			super(txt);
			setName(txt);
			super.setFont(new Font("宋体",Font.BOLD,keyboardSize));
		}
	}
	
	public static interface PaySucListener{
		void insertFirst(JSONObject data); 
	}
	
	private OrderQueryListener orderQuery =new OrderQueryListener(){
		@Override
		public void query() {
			orderPending();
		}
	};

}
